//配置Gitee令牌
var giteeToken = 'Gitee令牌'; 


dayjs.extend(window.dayjs_plugin_customParseFormat);
dayjs().format();

//验证登录状态
(sessionStorage.getItem('email') && sessionStorage.getItem('password')) ? [
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/loginstate',
        data: {
            email: sessionStorage.getItem('email'),
            password: sessionStorage.getItem('password'),
        },
        success: function (result) {
            if (result != '200') {
                window.location.href = '/login'
            }
        }
    })
] : [
    alert('请登录'),
    window.location.href = '/login'
]

//获取myinfo
var myinfo = [];
function adminmyinfo() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/myinfo',
        success: function (result) {
            if (result != '404') {
                myinfo = result;
                var sub = result.slogan.indexOf('<br />');
                $('.myPortrait').attr('src', result.imgsrc);
                $('.mySrc').text(result.imgsrc);
                $('.myID').val(result.ID);
                $('#slogan1').val(result.slogan.substring(0, sub).replaceAll('&nbsp;', ' '));
                $('#slogan2').val(result.slogan.substring(sub + 6).replaceAll('&nbsp;', ' '));
                $('.myUrl').text(result.blogurl);
            }
        }
    })
}

//声明用于存储图片信息的变量
var newimg = '';
var MIME = '';
var base64 = '';
var record = false;

//压缩头像
function conversion_head() {
    var portrait = document.getElementById('loadimg').files[0];

    if ((portrait.size / 1024) <= 100)
        getfileurl(portrait);
    else
        imageConversion.compressAccurately(portrait, 1000).then(res => {
            getfileurl(res);
        });
}

//选择本地头像
function getfileurl(portrait) {
    //初始化变量
    newimg = '';
    MIME = '';
    base64 = '';
    record = false;

    $('#myimg').find('.myPortrait').attr('src', window.webkitURL.createObjectURL(portrait))
    var reader = new FileReader();
    reader.onloadend = function () {
        newimg = reader.result;
        //截取上传图片的MIME类型
        MIME = newimg.substring(11, newimg.indexOf(';'));
        //截取上传图片的base64编码
        base64 = newimg.substring(newimg.indexOf(',') + 1);
        record = true;
    }
    if (portrait) {
        reader.readAsDataURL(portrait);
    }
}

//保存myinfo
function save() {
    $('#infomodify').removeClass('.modify').val('编辑');
    $('#id').removeClass('modify').attr('disabled', true);
    $('.mySlogan').removeClass('modify').attr('disabled', true);
    $('#editor').hide();
};

function saveinfo() {
    var nowtime = dayjs().$d;
    $('#infomodify').hasClass('.modify') ? [
        newinfo = {
            id: $('#id').val(),
            slogan: $('#slogan1').val().replaceAll(' ', '&nbsp;') + "<br />" + $('#slogan2').val().replaceAll(' ', '&nbsp;'),
            src: $('#myimg').find('.myPortrait')[0].src,
        },
        newinfo.id != oldinfo.id || newinfo.src != oldinfo.src || newinfo.slogan != oldinfo.slogan ? [
            //上传头像到gitee
            newinfo.src != oldinfo.src ?
                $.ajax({
                    type: 'POST',
                    data: 'json',
                    url: 'https://gitee.com/api/v5/repos/'+giteeID+'/dsrblog/contents/img/' + nowtime.getTime() + '.' + MIME,
                    data: {
                        access_token: giteeToken,
                        content: base64,
                        message: nowtime,
                    }
                }) : '',
            //上传信息到数据库
            record == true ? [
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: '/saveinfo',
                    data: {
                        id: $('#id').val(),
                        slogan: $('#slogan1').val().replaceAll(' ', '&nbsp;') + "<br />" + $('#slogan2').val().replaceAll(' ', '&nbsp;'),
                        imgsrc: 'https://gitee.com/'+giteeID+'/dsrblog/raw/master/img/' + nowtime.getTime() + '.' + MIME,
                    },
                    success: function (result) {
                        if ((result != 404)) {
                            save();
                            alert("保存成功");
                        } else {
                            alert("保存出错，请检查网络状况或重试");
                        }
                    }
                }),
                record = false
            ] : [
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: '/saveinfo',
                    data: {
                        id: $('#id').val(),
                        slogan: $('#slogan1').val().replaceAll(' ', '&nbsp;') + "<br />" + $('#slogan2').val().replaceAll(' ', '&nbsp;'),
                        imgsrc: oldinfo.src,
                    },
                    success: function (result) {
                        if ((result != 404)) {
                            save();
                            alert("保存成功");
                        } else {
                            alert("保存出错，请检查网络状况或重试");
                        }
                    }
                })
            ]
        ] : [
            save()
        ],
    ] : [
        $('#infomodify').addClass('.modify').val('保存'),
        $('#id').addClass('modify').attr('disabled', false),
        $('.mySlogan').addClass('modify').attr('disabled', false),
        $('#editor').show(),
        oldinfo = {
            id: $('#id').val(),
            slogan: $('#slogan1').val().replaceAll(' ', '&nbsp;') + "<br />" + $('#slogan2').val().replaceAll(' ', '&nbsp;'),
            src: $('#myimg').find('.myPortrait')[0].src
        },
    ]
}

//从服务器获取友链
function friendstate() {
    var approved, notapproved;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/friendAudit',
        success: function (result) {

            //初始化
            approved = `
                <p class="classification ModeBG">
                    已审核
                </p>`;
            notapproved = `
                <p class="classification ModeBG">
                    未审核
                </p>`;

            document.getElementById('state_0').innerHTML = notapproved;
            document.getElementById('state_1').innerHTML = approved;

            result.forEach(function (item) {
                (item.display == 1) ? [
                    approved += `
                        <div class="modecard ModeBG">
                            <img src="${item.imgsrc}"
                                class="friendlogo">
                            <div class="info">
                                <a class="friendID" href="${item.blogurl}" target="_blank">${item.id}</a>
                                <p class="friendslogan">${item.slogan.replaceAll('&nbsp;', ' ')}</p>
                            </div>
                            <div class="statecontrols">
                                <div class="priority">
                                    <p>优先级</p>
                                    <input type="text" name="priority" class="setpriority" maxlength="2"
                                        onkeydown="overwrite(this)" onkeyup="priorityMax(this)" value="${item.priority}">
                                </div>
                                <div class="decision">
                                    <input type="button" value="删除" class="rejected" onclick="rejected(this, 'delete')">
                                    <input type="button" value="修改" class="agree" onclick="agree(this,'change')">
                                </div>
                            </div>
                        </div>
                    `
                ] : [
                    notapproved += `
                        <div class="modecard ModeBG">
                            <img src="${item.imgsrc}"
                                class="friendlogo">
                            <div class="info">
                                <a class="friendID" href="${item.blogurl}" target="_blank">${item.id}</a>
                                <p class="friendslogan">${item.slogan.replaceAll('&nbsp;', ' ')}</p>
                            </div>
                            <div class="statecontrols">
                                <div class="priority">
                                    <p>优先级</p>
                                    <input type="text" name="priority" class="setpriority" maxlength="2"
                                        onkeydown="overwrite(this)" onkeyup="priorityMax(this)" value="${item.priority}">
                                </div>
                                <div class="decision">
                                    <input type="button" value="驳回" class="rejected" onclick="rejected(this, 'rejected')">
                                    <input type="button" value="通过" class="agree" onclick="agree(this,'agree')">
                                </div>
                            </div>
                        </div>
                    `
                ];
            });
            (notapproved != `
                <p class="classification ModeBG">
                    未审核
                </p>`) ? $('#state_0').show() : $('#state_0').hide();
            document.getElementById('state_0').innerHTML = notapproved;
            document.getElementById('state_1').innerHTML = approved;
        }
    })
}

//优先级输入框新的值覆盖旧的值
function overwrite(obj) {
    $(obj).val(null);
}
//限制优先级输入不小于0，不大于3，并且不是非数字
function priorityMax(obj) {

    if ($(obj).val() > 3)
        $(obj).val('3');
    else if ($(obj).val() < 0)
        $(obj).val('0');
    else if (isNaN($(obj).val()))
        $(obj).val('0');
}

//删除或驳回友链申请
function rejected(obj, state) {
    confirm('该操作无法逆转') ? [
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/rejected',
            data: {
                blogurl: $(obj).parents('.modecard').find('.friendID').attr('href')
            },
            success: function (result) {
                (result != 404) ? [
                    state == 'rejected' ? prompt('已驳回该申请') : prompt('已删除该友链'),
                    friendstate(),
                ] : [
                    state == 'rejected' ? prompt('驳回失败，请重试') : prompt('删除失败，请重试'),
                ];
            }
        })
    ] : [];
}


//通过或修改添加友链
function agree(obj, state) {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/agree',
        data: {
            blogurl: $(obj).parents('.modecard').find('.friendID').attr('href'),
            priority: $(obj).parents('.modecard').find('.setpriority').val(),
        },
        success: function (result) {
            (result != 404) ? [
                state == 'agree' ? prompt('已通过该申请') : prompt('修改成功'),
                friendstate(),
            ] : state == 'agree' ? prompt('通过失败，请重试') : prompt('修改失败，请重试');
        }
    })
}

//友链申请变更提示
function prompt(text) {
    $('#prompt').show().find('p').text(text);

    setTimeout(() => {
        $('#prompt').hide();
    }, 4000);
}

//返回上一级
function infoback() {
    $('#myinfobox').hide();
    $('#myinfomask').hide();
}

function infoopen() {
    $('#myinfobox').show();
    $('#myinfomask').show();
}

//发布动态

//构建结构体数组用于存放图片的MIME类型和base64编码
var imgArray = {
    MIME: Array(),
    base64: Array(),
}
//声明一个数组用于存放图片的url
var urllist = new Array();

//压缩图片
function conversion() {
    var portrait = document.getElementById('upload').files[0];

    if ((portrait.size / 1024) <= 100)
        getdynamicurl(portrait);
    else
        imageConversion.compressAccurately(portrait, 1000).then(res => {
            getdynamicurl(res);
        });
}

//选择本地图片
function getdynamicurl(portrait) {
    var length = urllist.length;

    urllist[length] = window.webkitURL.createObjectURL(portrait);

    displayimg(length);

    var reader = new FileReader();

    reader.onloadend = function () {

        //截取上传图片的MIME类型
        imgArray.MIME[length] = reader.result.substring(11, reader.result.indexOf(';'));
        //截取上传图片的base64编码
        imgArray.base64[length] = reader.result.substring(reader.result.indexOf(',') + 1);
    }
    if (portrait) {
        reader.readAsDataURL(portrait);
    }
    if (length >= 8) {
        $('#img_upload').hide();
    }
}

//删除已选照片
function deleteurl(obj) {
    let i = $(obj).parent('.imgbox').index() - 1;

    for (i; i < urllist.length; i++) {
        urllist[i] = urllist[i + 1];
        imgArray.MIME[i] = imgArray.MIME[i + 1];
        imgArray.base64[i] = imgArray.base64[i + 1];
    }

    //删除表尾的空元素
    urllist.length -= 1;
    imgArray.MIME.length -= 1;
    imgArray.base64.length -= 1;

    displayimg(urllist.length)
}

// 显示添加的照片
var imglist;
function displayimg(max) {
    //初始化
    if (max >= 8) {
        imglist = '';
    }
    else {
        imglist = `
        <div id="img_upload" class="ModeBG">
            <input type="file" name="upload" accept="image/*" lay-verify="required" id="upload" onchange="conversion()">
            <div id="uploadmask">
                <div id="mask" class="modecard"></div>
            </div>
            <i id="wordstext" class="fa fa-image"></i>
        </div>
    `;
    };

    urllist.forEach(function (item) {
        imglist += `
                    <div class="imgbox">
                        <button type="button" class="delBtn" onclick="deleteurl(this)">
                            <i class="fa fa-plus"></i>
                        </button>
                        <div class="img">
                            <img src="${item}">
                        </div>
                    </div>
                `
    });
    document.getElementById('imgArray').innerHTML = imglist;
}

//清空所有内容
function clearAll() {
    //清空图片
    urllist.length = 0;
    imgArray.MIME.length = 0;
    imgArray.base64.length = 0;
    displayimg(0);

    //清空文字
    $('#dynamictext').val('');
}

//打开动态发布
function enterdynamic() {
    $('#dynamic').show();
    $('#friendstate').hide();
    $('#menu').hide();
}
//退出动态发布
function exitdynamic() {
    if ($('#dynamictext').val() != '' || urllist.length != 0) {
        confirm('返回后将会清空所有内容') ? [
            clearAll(),
            $('#dynamic').hide(),
            $('#friendstate').show(),
            $('#menu').show(),
        ] : []
    }
    else {
        $('#dynamic').hide();
        $('#friendstate').show();
        $('#menu').show();
    }

}

//打开音乐库
function entermusic() {
    $('#music').show();
    $('#friendstate').hide();
    $('#menu').hide();
}
//退出音乐库
function exitmusic() {
    $('#music').hide();
    $('#friendstate').show();
    $('#menu').show();
}

//清空链接栏
function clearUrl() {
    $('#musicUrl').val('');
    player.off("play");
    player.off("pause");
    player.pause();
}

function loadtogitee() {

    var nowtime = dayjs().$d;
    var length = imgArray.base64.length;

    var MIMEList = '';

    $('#load_prompt').find('div').text('LOADING...');
    $('#load_prompt').show("0", function () {
        if (length != 0) {
            //上传图片到Gitee
            for (let i = 0; i < length; i++) {
                MIMEList += (imgArray.MIME[i] + ';');
                $.ajax({
                    type: 'POST',
                    data: 'json',
                    async: false,
                    timeout: 30000,
                    url: 'https://gitee.com/api/v5/repos/'+giteeID+'/figure/contents/dynamic/' + nowtime.getTime() + '/' + nowtime.getTime() + '_' + i + '.' + imgArray.MIME[i],
                    data: {
                        access_token: giteeToken,
                        content: imgArray.base64[i],
                        message: nowtime,
                    },
                    success: function () {
                        if (i == length - 1)
                            uploadMysql(MIMEList, length, nowtime);
                    },
                    error: function () {
                        alert("图片上传失败");
                        $('#load_prompt').hide();
                    }
                });
            }
        }
        else {
            uploadMysql('', 0, nowtime);
        }
    })
}

//上传动态内容和图片地址到数据库
function uploadMysql(MIMEList, length, datatime) {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/uploadDynamic',
        data: {
            mime: MIMEList,
            length: length,
            text: $('#dynamictext').val().replaceAll(' ', '&nbsp;').replaceAll('\n', '<br />'),
            imgsrc: (length != 0) ? 'https://gitee.com/'+giteeID+'/figure/raw/master/dynamic/' + datatime.getTime() + '/' + datatime.getTime() + '_' : '',
        },
        success: function (result) {
            if ((result != 404)) {
                clearAll();
                $('#load_prompt').hide();
                alert("发布成功");
            } else {
                $('#load_prompt').hide();
                alert("发布失败");
            }
        }
    })
}